package com.example.okhttpdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    ImageView imageView;

    private static final int WRITE_REQUEST_CODE = 43;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
      private static String[] PERMISSIONS_STORAGE = {
             Manifest.permission.WRITE_EXTERNAL_STORAGE };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        verifyStoragePermissions(this);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.iv_image);
        httpDownload();
    }

    private void createFile(String mimeType, String fileName) {
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);

        // Filter to only show results that can be "opened", such as
        // a file (as opposed to a list of contacts or timezones).
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        // Create a file with the requested MIME type.
        intent.setType(mimeType);
        intent.putExtra(Intent.EXTRA_TITLE, fileName);
        startActivityForResult(intent, WRITE_REQUEST_CODE);
    }

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
            int permission = ActivityCompat.checkSelfPermission(activity,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
                 // We don't have permission so prompt the user
                 ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                                 REQUEST_EXTERNAL_STORAGE);
             }
     }

    public static String getDownloadPath(Context context, String fileName) {
        return getDownloadPath(context) + File.separator + fileName;
    }

    public static String getDownloadPath(Context context) {
        return context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
    }

    public static void copyPrivateImgToCommen(Context context, String orgFilePath, String displayName) {
        ContentValues values = new ContentValues();
        values.put(MediaStore.Files.FileColumns.DISPLAY_NAME, displayName);
        values.put(MediaStore.Files.FileColumns.TITLE, displayName);
        values.put(MediaStore.Files.FileColumns.MIME_TYPE, "image/png");
        values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES+File.separator+"test");
        Uri external = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver resolver = context.getContentResolver();
        Uri insertUri = resolver.insert(external, values);
        Log.e("cxp", "copyPrivateImgToCommen: " + insertUri.toString() );
        Log.e("cxp", "xxxxxxxxxxx: " + Uri.parse(insertUri.toString()));
        InputStream ist = null;
        OutputStream ost = null;
        try {
            ist = new FileInputStream(new File(orgFilePath));
            if (insertUri != null) {
                ost = resolver.openOutputStream(insertUri);
            }
            if (ost != null) {
                byte[] buffer = new byte[4096];
                int byteCount = 0;
                while ((byteCount = ist.read(buffer)) != -1) {
                    ost.write(buffer, 0, byteCount);
                }
            }
        } catch (IOException e) {

        } finally {
            try {
                if (ist != null) {
                    ist.close();
                }
                if (ost != null) {
                    ost.close();
                }
            } catch (IOException e) {

            }
        }
    }

    public void httpDownload(){
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request
                .Builder()
                .get()
                .url("https://avatar.csdn.net/B/0/1/1_new_one_object.jpg")
//                .url("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201805%2F31%2F002415vf29rfcednrdrw83.jpg&refer=http%3A%2F%2Fattach.bbs.miui.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1622105968&t=c7b18bb218f8fca04b53ecf900da0c8a")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Toast.makeText(MainActivity.this, "download failed", Toast.LENGTH_SHORT).show();
            }



            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                InputStream inputStream = response.body().byteStream();
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setImageBitmap(bitmap);
                    }
                });
//                Log.e("cxp", "onResponse: " + String.valueOf(Environment.getExternalStorageDirectory()));
//                File file = new File(String.valueOf(Environment.getExternalStorageDirectory()),"image.png");
                Log.e("cxp", "onResponse: " + MainActivity.this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() );
                try {
                    File file = new File(getDownloadPath(MainActivity.this,"image.png"));
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
//                    byte[] temp = new byte[128];
//                    int length;
//                    while ((length=inputStream.read(temp))!= -1){
//                        fileOutputStream.write(temp,0,length);
//                    }
//                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
                    bitmap.compress(Bitmap.CompressFormat.PNG,100,fileOutputStream);
                    copyPrivateImgToCommen(MainActivity.this,MainActivity.this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()+File.separator+"image.png","image.png");
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}